package top.pmwly.service;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Collection;

/**
 * @author Herther
 * @version 1.0.0
 * @ClassName MyserviceImpl.java
 * @Description 实现自定义的权限拦截
 * @createTime 2021年08月19日 15:17:00
 */
@Service
public class MyserviceImpl implements Myservice{


    /**
     * 实现myprocess方法
     * @param request
     * @param authentication
     * @return
     */
    @Override
    public boolean hasPremission(HttpServletRequest request, Authentication authentication) {
        Object obj = authentication.getPrincipal();
        //判断是否为User对象 springsecurity
        if (obj instanceof UserDetails){
            UserDetails userDetails = (UserDetails) obj;
            //拿到 权限集合
            Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities();
            //GrantedAuthority 实现类判断，是否拥有权限
            //获取 uri
            String requestURI = request.getRequestURI();
            //单个判断 返回是否拥有角色的
            boolean contains = authorities.contains(new SimpleGrantedAuthority(requestURI));
            return contains;
        }
        return false;
    }
}
